<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>备件管理系统</title>
  <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
  <link rel="icon" href="img/favicon.ico" type="image/x-icon">
  <style>
    /* 更新侧边导航栏样式 */
    .sidebar {
      position: fixed;
      top: 60px; /* header高度 */
      left: 0;
      width: 100px; /* 默认宽度为100px */
      height: calc(100vh - 60px); /* 减去header高度 */
      background-color: #f0f4f8; /* 更新背景颜色 */
      color: #333; /* 更新文字颜色 */
      transition: width 0.3s ease; /* 添加平滑过渡效果 */
      z-index: 1000;
      border-top-left-radius: 0;
    }
    /* .sidebar:hover {
      width: 200px;  鼠标悬停时不再变大  */
    /* } */
    .sidebar h3 {
      text-align: center;
      padding: 20px 0;
      margin: 0;
      font-size: 18px;
      display: block; /* 默认显示标题 */
      color: #333; /* 更新标题颜色 */
    }
    .sidebar ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }

    .sidebar li {
      padding: 15px;
      border-bottom: 1px solid #e9ecef;
      display: flex;
      align-items: center;
      position: relative;
      background-color: #f0f4f8;
      justify-content: center; /* 新增：默认居中 */
      transition: justify-content 0.3s;
    }
    .sidebar:hover li {
      justify-content: center; /* 悬停时依然居中 */
    }
    .sidebar a {
      color: #333;
      text-decoration: none;
      display: flex;
      align-items: center;
      width: 100%;
      justify-content: center; /* 新增：链接内容居中 */
    }
    .sidebar i {
      margin-right: 10px;
      font-size: 18px;
      color: #333; /* 更新图标颜色 */
    }

    /* 更新二级导航栏样式 */
    .sub-sidebar {
      position: absolute; /* 相对于一级导航栏项定位 */
      top: 0;
      left: 100px; /* 紧贴一级导航栏右侧，和sidebar宽度一致 */
      width: 250px; /* 默认显示 */
      height: 250px;
      background-color: #f0f4f8; /* 更新背景颜色 */
      color: #333; /* 更新文字颜色 */
      overflow-y: auto;
      z-index: 999;
      transition: width 0.3s ease;
      display: none; /* 新增：默认隐藏 */
    }
    .sub-sidebar ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }
    .sub-sidebar li {
      padding: 10px 20px;
      border-bottom: 1px solid #e9ecef;
      background-color: #f0f4f8; /* 更新背景颜色 */
    }
    .sub-sidebar li:hover {
      background-color: #dfe9f3; /* 更新悬停背景颜色 */
      cursor: pointer;
    }
    .sub-sidebar a {
      color: #333; /* 更新链接颜色 */
      text-decoration: none;
    }

    /* 当前选中状态 */
    .sidebar li.active,
    .sub-sidebar li.active {
      background-color: #007bff;
      color: white;
    }

    /* 新增：鼠标悬停时显示二级导航栏 */
    .sidebar li:hover .sub-sidebar {
      display: block;
      left: 100px; /* 保证弹框紧贴当前sidebar宽度 */
    }
  </style>
</head>
<body>
<div id="app">
  <!-- 更新一级侧边导航栏 -->
  <div class="sidebar">
    <h3>功能菜单</h3>
    <ul>
      <!-- 供应商 -->
      <li :class="{ active: activeSubSidebar === 'supplier' }">
        <a href="#"><i class="el-icon-user"></i>供应商</a>
        <div class="sub-sidebar">
          <ul>
            <li><a href="/operation/supplier_management.html">供应商</a></li>
            <li><a href="/operation/supplier_evaluation.html">供应商评价</a></li>
          </ul>
        </div>
      </li>
      <!-- 设备 -->
      <li :class="{ active: activeSubSidebar === 'equipment' }">
        <a href="#"><i class="el-icon-s-tools"></i>设备</a>
        <div class="sub-sidebar">
          <ul>
            <li><a href="/operation/sparepart_management.html">设备管理</a></li>
          </ul>
        </div>
      </li>
      <!-- 库存 -->
      <li :class="{ active: activeSubSidebar === 'inventory' }">
        <a href="#"><i class="el-icon-goods"></i>库存</a>
        <div class="sub-sidebar">
          <ul>
            <li><a href="/operation/inventory_alerts.html">库存预警</a></li>
            <li><a href="/operation/inventory_reports.html">库存报告</a></li>
            <!-- 新增：库存调整 -->
            <li><a href="/operation/inventory_adjustments.html">库存调整</a></li>
          </ul>
        </div>
      </li>
      <!-- 批次 -->
      <li :class="{ active: activeSubSidebar === 'batch' }">
        <a href="#"><i class="el-icon-takeaway-box"></i>批次</a>
        <div class="sub-sidebar">
          <ul>
            <li><a href="/operation/outbound_records.html">出库记录</a></li>
            <li><a href="/operation/inbound_records.html">入库记录</a></li>
          </ul>
        </div>
      </li>
    </ul>
  </div>

  <el-container style="height: 100vh;">
    <el-header style="background-color: #007bff; color: white; display: flex; align-items: center; justify-content: space-between; height: 60px; padding-left: 100px; box-sizing: border-box; border-top-left-radius: 0; position: fixed; top: 0; left: 0; right: 0; z-index: 1100;">
      <h2 style="margin: 0;">备件管理系统</h2>
      <el-button type="default" size="small" style="background-color: #e0e0e0; color: #333; border: none;" @click="logout">退出</el-button>
    </el-header>
    <el-main style="padding-left: 100px;">
      <!-- 库存预警表格（复制自 operation/inventory_alerts.html） -->
      <div style="margin-top: 80px;">
        <h3>库存预警</h3>
        <!-- 搜索框和退出按钮已移除，仅保留表格 -->
        <el-table :data="filteredInventoryAlerts" border style="width: 100%">
          <el-table-column prop="alertid" label="ID"></el-table-column>
          <el-table-column prop="sparepartid" label="备件ID"></el-table-column>
          <el-table-column prop="totalQuantity" label="总库存量"></el-table-column>
          <el-table-column prop="status" label="状态"></el-table-column>
        </el-table>
      </div>
      <!-- 两个图表容器并排显示（复制自 dashboard.html） -->
      <div style="margin-top: 40px; display: flex; gap: 32px;">
        <!-- 图表容器1 -->
        <div style="width: 50%; border: 1px solid #ddd; padding: 15px; box-sizing: border-box; position: relative;">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <h3>{{ currentChart === 'funds' ? '资金占用分布' : '库存调整趋势' }}</h3>
            <el-button
              type="primary"
              size="small"
              @click="toggleChart"
              style="position: absolute; right: 15px; top: 15px;">
              {{ currentChart === 'funds' ? '库存调整趋势' : '资金占用分布' }}
            </el-button>
          </div>
          <div id="funds-pie-chart" v-show="currentChart === 'funds'" style="width: 100%; height: 400px;"></div>
          <div id="adjustments-line-chart" v-show="currentChart === 'adjustments'" style="width: 100%; height: 400px;"></div>
        </div>
        <!-- 图表容器2 -->
        <div style="width: 50%; border: 1px solid #ddd; padding: 15px; box-sizing: border-box; position: relative;">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <h3>库存报表 - 备件ID与周转率柱状图</h3>
          </div>
          <div id="turnover-bar-chart" style="width: 100%; height: 400px; margin-top: 20px;"></div>
        </div>
      </div>
    </el-main>
  </el-container>
</div>

<!-- 引入 Vue + Axios + Element Plus -->
<script src="https://unpkg.com/vue@3.2.36/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/element-plus"></script>

<script>
  const { createApp } = Vue;
  const apiClient = axios.create({
    //本机地址
    //baseURL: 'http://localhost:8086',
    //服务器 地址
    baseURL: 'http://8.137.85.243:8086',
    timeout: 5000
  });
  let echartsScriptLoaded = false;
  function loadEchartsScript(callback) {
    if (echartsScriptLoaded) { callback(); return; }
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js';
    script.onload = () => { echartsScriptLoaded = true; callback(); };
    document.head.appendChild(script);
  }
  const app = createApp({
    data() {
      return {
        activeTab: 'user',
        activeSubSidebar: null,
        inventoryAlertsList: [],
        searchAlertQuery: '',
        inventoryReports: [],
        searchReportQuery: '',
        inventoryAdjustmentsList: [],
        currentAdjustmentsPage: 1,
        adjustmentsPageSize: 10,
        currentChart: 'funds'
      };
    },
    computed: {
      filteredInventoryAlerts() {
        let list = this.inventoryAlertsList.filter(item => item.status === '短缺');
        if (!this.searchAlertQuery) {
          return list;
        }
        return list.filter(item =>
          item.sparepartid && item.sparepartid.toString().includes(this.searchAlertQuery)
        );
      },
      filteredInventoryReports() {
        if (!this.searchReportQuery) {
          return this.inventoryReports;
        }
        return this.inventoryReports.filter(item =>
          item.sparepartid && item.sparepartid.toString().includes(this.searchReportQuery)
        );
      },
      filteredInventoryAdjustmentsList() {
        return this.inventoryAdjustmentsList;
      },
      paginatedInventoryAdjustmentsList() {
        const start = (this.currentAdjustmentsPage - 1) * this.adjustmentsPageSize;
        const end = start + this.adjustmentsPageSize;
        return this.filteredInventoryAdjustmentsList.slice(start, end);
      }
    },
    mounted() {
      this.loadInventoryAlerts();
      this.loadInventoryReports();
      this.loadInventoryAdjustments();
      loadEchartsScript(() => {
        this.$nextTick(() => {
          this.renderFundsPieChart();
          this.renderAdjustmentsChart();
          this.renderTurnoverBarChart();
        });
      });
    },
    methods: {
      async loadInventoryAlerts() {
        try {
          const res = await apiClient.get('/api/inventoryalerts/listall');
          this.inventoryAlertsList = res.data;
        } catch (e) {
          this.inventoryAlertsList = [];
        }
      },
      async loadInventoryReports() {
        try {
          const res = await apiClient.get('/api/inventoryreports/listall');
          this.inventoryReports = res.data;
          this.$nextTick(() => {
            if (window.echarts) {
              this.renderFundsPieChart();
              this.renderTurnoverBarChart();
            }
          });
        } catch (e) {
          this.inventoryReports = [];
        }
      },
      async loadInventoryAdjustments() {
        try {
          const res = await apiClient.get('/api/inventoryadjustments/listall');
          this.inventoryAdjustmentsList = res.data;
          this.$nextTick(() => {
            if (window.echarts) this.renderAdjustmentsChart();
          });
        } catch (e) {
          this.inventoryAdjustmentsList = [];
        }
      },
      toggleChart() {
        this.currentChart = this.currentChart === 'funds' ? 'adjustments' : 'funds';
        this.$nextTick(() => {
          if (this.currentChart === 'funds' && window.echarts) {
            this.renderFundsPieChart();
          } else if (this.currentChart === 'adjustments' && window.echarts) {
            this.renderAdjustmentsChart();
          }
        });
      },
      renderFundsPieChart() {
        if (!window.echarts) return;
        const chartDom = document.getElementById('funds-pie-chart');
        if (!chartDom || this.currentChart !== 'funds') return;
        const data = this.inventoryReports || [];
        const pieData = data
          .filter(item => item.occupiedFunds && item.sparepartid)
          .map(item => ({
            value: Number(item.occupiedFunds),
            name: String(item.sparepartid)
          }));
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle',
            formatter: name => `备件ID: ${name}`
          },
          series: [
            {
              name: '资金占用',
              type: 'pie',
              radius: '60%',
              center: ['60%', '50%'],
              data: pieData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                formatter: '{b}: {c}'
              }
            }
          ]
        };
        const chart = window.echarts.init(chartDom);
        chart.setOption(option);
      },
      renderAdjustmentsChart() {
        if (!window.echarts) return;
        const chartDom = document.getElementById('adjustments-line-chart');
        if (!chartDom || this.currentChart !== 'adjustments') return;
        const data = this.inventoryAdjustmentsList || [];
        const sorted = [...data].sort((a, b) => {
          if (!a.adjustmentDate || !b.adjustmentDate) return 0;
          return new Date(a.adjustmentDate) - new Date(b.adjustmentDate);
        });
        const xData = sorted.map(item => item.adjustmentDate || '');
        const yData = sorted.map(item => Number(item.difference) || 0);
        const option = {
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: xData, name: '调整日期' },
          yAxis: { type: 'value', name: '差异量' },
          series: [{
            data: yData,
            type: 'line',
            smooth: true,
            areaStyle: {},
            name: '差异量',
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: { width: 3 }
          }]
        };
        const chart = window.echarts.init(chartDom);
        chart.setOption(option);
      },
      renderTurnoverBarChart() {
        if (!window.echarts) return;
        const chartDom = document.getElementById('turnover-bar-chart');
        if (!chartDom) return;
        const data = this.filteredInventoryReports || [];
        const xData = data.map(item => item.sparepartid);
        const yData = data.map(item => Number(item.turnoverRate) || 0);
        const option = {
          title: { text: '备件ID与周转率柱状图', left: 'center' },
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: xData, name: '备件ID' },
          yAxis: { type: 'value', name: '周转率' },
          series: [{
            data: yData,
            type: 'bar',
            name: '周转率',
            itemStyle: { color: '#409EFF' }
          }]
        };
        const chart = window.echarts.init(chartDom);
        chart.setOption(option);
      },
      async deleteInventoryAdjustments(id) {
        if (!confirm('确定删除？')) return;
        await apiClient.delete(`/api/inventoryadjustments/delete/${id}`);
        this.loadInventoryAdjustments();
      },
      logout() {
        window.location.href = '/login.html';
      },
      showSubSidebar(subSidebar) {
        this.activeSubSidebar = this.activeSubSidebar === subSidebar ? null : subSidebar;
      }
    }
  });
  app.use(ElementPlus);
  app.mount('#app');
</script>
</body>
</html>
